package cc.ucanuup.service.base.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import cc.ucanuup.common.support.easyui.inter.EasyuiQuery;
import cc.ucanuup.common.support.easyui.view.EasyuiTree;
import cc.ucanuup.config.security.util.AppUtil;
import cc.ucanuup.config.security.util.UserInfo;
import cc.ucanuup.service.base.dao.UpMenusJPA;
import cc.ucanuup.service.base.dto.MenuDto;
import cc.ucanuup.service.base.entity.Manager;
import cc.ucanuup.service.base.entity.UpMenus;
import cc.ucanuup.service.base.entity.UpUser;
import cc.ucanuup.service.base.inter.ManagerService;
import cc.ucanuup.service.base.inter.UpMenuservice;
import cc.ucanuup.service.base.inter.UpUserService;


/**
 * Description: TODO[描述该类概要功能介绍]
 *
 * @author guwenbin
 * @date 2018年2月1日
 * @version 1.0
 */
@Service
public class UpMenuserviceImpl implements UpMenuservice {
	private static final Logger logger = LoggerFactory.getLogger(UpMenuserviceImpl.class);
	@Autowired
	private UpMenusJPA upMenuJPA;
	@Autowired
	private ManagerService managerService;
	@Autowired
	private UpUserService upUserService;
	@Autowired
	private UpMenuservice UpMenuservice;

	@Override
	public List<UpMenus> findAll() {

		return upMenuJPA.findAll();
	}

	@Override
	public Page<UpMenus> queryTopMenusAndSortIt(EasyuiQuery bzPage) {
		Pageable pageable= new PageRequest(bzPage.getPageNo(), bzPage.getPageSize());
		return upMenuJPA.queryTopMenusAndSortIt(pageable);
	}

	@Override
	public UpMenus findOne(String id) {

		return upMenuJPA.findOne(id);
	}

	@Override
	public List<UpMenus> findMenusByLevel(Integer menuLevel) {

		return upMenuJPA.findMenusByLevel(menuLevel);
	}

	@Override
	public UpMenus save(UpMenus menu) {

		return upMenuJPA.save(menu);
	}

	@Override
	public List<UpMenus> findMenusByFid(String fid) {

		return upMenuJPA.findMenusByFid(fid);
	}

	@Override
	public int updateMenusDeleteStatus(String id) {
		List<UpMenus> menuList = upMenuJPA.findMenusById(id);
		for(int i=0;i<menuList.size();i++){
			menuList.get(i).setDeleted(1);
		}
		return upMenuJPA.save(menuList).size();
	}

	@Override
	public List<EasyuiTree> findRoleMenusStatusListByRoleId(String roleId) {
		List<EasyuiTree> treeList  = new ArrayList<EasyuiTree>();
		// 获取所有的激活的菜单
		EasyuiTree tree = null ;
		List<List<UpMenus>> allActiveMenus = getThreeLevelList(upMenuJPA.findAllActiveMenus());
		List<List<UpMenus>> allpowerMenus = getThreeLevelList(upMenuJPA.findMenusByRoleId(roleId));
		for(UpMenus mu :allActiveMenus.get(0)){
			tree = new EasyuiTree();
			// 如果权限里有,设置选中
			tree.setId(mu.getId());
			tree.setText(mu.getMenuName());
			/*			for(Menu pmu :allpowerMenus.get(0)){
				if(mu.getId().equals(pmu.getId())){
					tree.setChecked(true);
				}
			}*/
			// 查询第二级别菜单信息
			for(UpMenus second :allActiveMenus.get(1)){
				if(second.getFid()!=null && second.getFid().equals(mu.getId())){
					EasyuiTree secondTree = new EasyuiTree();
					secondTree.setId(second.getId());
					secondTree.setText(second.getMenuName());
					// 遍历3级菜单信息
					for(UpMenus thread :allActiveMenus.get(2)){
						if(thread.getFid()!=null && thread.getFid().equals(second.getId())){
							EasyuiTree threadTree = new EasyuiTree();
							threadTree.setId(thread.getId());
							threadTree.setText(thread.getMenuName());
							// 二级菜单设置选中
							for(UpMenus pmu3 :allpowerMenus.get(2)){
								if(thread.getId().equals(pmu3.getId())){
									threadTree.setChecked(true);
								}
							}
							secondTree.getChildren().add(threadTree);
						}
					}
					// 二级菜单设置选中
					if(secondTree.getChildren()!=null && secondTree.getChildren().size()<=0){
						for(UpMenus pmu2 :allpowerMenus.get(1)){
							if(secondTree.getId().equals(pmu2.getId())){
								secondTree.setChecked(true);
							}
						}

					}
					tree.getChildren().add(secondTree);
				}
			}
			// 1级菜单设置选中
			if(tree.getChildren()!=null && tree.getChildren().size()<=0){
				//System.out.println(tree.getText());
				for(UpMenus pmu1 :allpowerMenus.get(0)){
					//System.out.println(tree.getId()+"]]]]]]]]");
					//System.out.println(pmu1.getId());
					if(tree.getId().equals(pmu1.getId())){
						tree.setChecked(true);
					}
				}
			}
			treeList.add(tree);
		}
		// 或所有
		return treeList;
	}

	private List<List<UpMenus>>  getThreeLevelList(final List<UpMenus> menuList){
		List<List<UpMenus>> menu  = new ArrayList<List<UpMenus>>(3);
		ArrayList<UpMenus> top = new ArrayList<UpMenus>();
		ArrayList<UpMenus> second = new ArrayList<UpMenus>();
		ArrayList<UpMenus> thread = new ArrayList<UpMenus>();
		if(menuList!=null){
			for(UpMenus mu :menuList){
				if(mu == null){
					break;
				}
				switch (mu.getMenuLevel()) {
					case 0: top.add(mu); break; //  top level menu
					case 1: second.add(mu);break; // second level menu
					case 2: thread.add(mu);break; // thread level menu
					default:;break; // just put it here, do nothing.
				}
			}
		}
		menu.add(top);
		menu.add(second);
		menu.add(thread);
		return menu;
	}

	@Override
	public List<MenuDto> findAllMenusByUserAccount(String userAccount) {

		// 判断是否是超级管理员
		List<UpMenus> muList = null;
		Manager manager = managerService.findOneByUserAccount(userAccount);

		if(manager!=null){
			muList=upMenuJPA.findAllActiveMenus();
		}else{
			muList=upMenuJPA.findAllActiveMenusByUserAccount(userAccount);
			UserInfo info = AppUtil.getSrmUserInfo();
			if(info.isSpLogin()){ // 如果是登陆 指定供应商的状态 那么就获取指定供应商的信息
				UpUser sp = upUserService.findSupplierByName(info.getSpCode());
				List<UpMenus> defaultList = UpMenuservice.findMenusBySptype(sp.getUserType());
				if(defaultList!=null && defaultList.size()>0){
					muList.addAll(defaultList);
				}
			}else{
				UpUser sp = upUserService.findSupplierByName(info.getUserAccount());
				List<UpMenus> defaultList = UpMenuservice.findMenusBySptype(sp.getUserType());
				if(defaultList!=null && defaultList.size()>0){
					muList.addAll(defaultList);
				}
			}
		}
		// 去重复
		Set<UpMenus> set = new HashSet<UpMenus>();
		for(UpMenus sm : muList ){
			set.add(sm);
		}
		// 转回原来的集合
		muList.clear();
		for(UpMenus sm : set ){
			muList.add(sm);
		}

		Collections.sort(muList, new Comparator<UpMenus>() {
			/*
			 * 返回负数表示：o1 小于o2，
			 * 返回0 表示：o1和o2相等，
			 * 返回正数表示：o1大于o2。
			 */
			@Override
			public int compare(UpMenus o1, UpMenus o2) {

				//按照学生的年龄进行升序排列
				if(o1.getOrderLevel() > o2.getOrderLevel()){
					return -1;
				}
				if(o1.getOrderLevel() == o2.getOrderLevel()){
					return 0;
				}
				return 1;
			}
		});
		//Get list  ( 1  2  3 level in menuList)  .
		List<List<UpMenus>> menuList  = getThreeLevelList(muList);
		//do some thing , to get  List<MenuDto> object .
		List<MenuDto> top = new ArrayList<MenuDto>(50);
		MenuDto one = null;
		MenuDto two = null;
		MenuDto three = null;
		//First :Get the Top level menu button
		for(int i= menuList.get(0).size();i>0;i--){
			one = new MenuDto();
			one.setMenu(menuList.get(0).get(i-1));
			//Second :Get the second level menu button
			for(int j= menuList.get(1).size();j>0;j--){
				if(menuList.get(1).get(j-1).getFid() != null && menuList.get(1).get(j-1).getFid().equals(one.getMenu().getId())){
					if(one.getSun() == null ) {
						one.setSun(new ArrayList<MenuDto>());
					}
					two = new MenuDto();
					two.setMenu(menuList.get(1).get(j-1));
					//Thread :Get the thread level menu button
					for(int k= menuList.get(2).size();k>0;k--){
						if(menuList.get(2).get(k-1).getFid() != null && menuList.get(2).get(k-1).getFid().equals(two.getMenu().getId())){
							if(two.getSun() == null ) {
								two.setSun(new ArrayList<MenuDto>());
							}
							three = new MenuDto();
							three.setMenu(menuList.get(2).get(k-1));
							two.getSun().add(three);
						}
					}
					// 判断是否是自定义的菜单
					/*					if("自定义菜单".equals(two.getMenu().getMenuName())){
						List<Menu>  personalStyle = menuJPA.findPersonalStyleMenusByAccount(userAccount);
						if(personalStyle!=null && personalStyle.size()>0){
							for(Menu mu : personalStyle){
								if(two.getSun() == null ) {
									two.setSun(new ArrayList<MenuDto>());
								}
								three = new MenuDto();
								three.setMenu(mu);
								two.getSun().add(three);
							}
						}

					}*/
					//Thread : end
					one.getSun().add(two);
				}
			}
			//Second :end
			top.add(one);
		}
		//First :end
		return top;
	}

	@Override
	public Set<String> findPermissionsByUserAccount(UpUser sp) {
		Set<String> permission = new HashSet<String>();
		List<UpMenus> muList = null;
		Manager manager = managerService.findOneByUserAccount(sp.getUserAccount());
		if(manager!=null){
			muList=upMenuJPA.findAllActiveMenus();
		}else{
			muList=upMenuJPA.findAllActiveMenusByUserAccount(sp.getUserAccount());
		}
		List<UpMenus> defaultList = UpMenuservice.findMenusBySptype(sp.getUserType());
		if(muList== null){
			muList = defaultList;
		}else{
			if(defaultList!=null){
				muList.addAll(defaultList);
			}
		}
		for(UpMenus sm : muList){
			permission.add(sm.getMenuPermission());
		}
		return permission;
	}

	/**
	 * @Description:  通过供应商类型查询资源菜单信息
	 * @author WenBin
	 *
	 * @param spType
	 * @return
	 * @update [日期YYYY-MM-DD] [更改人姓名][变更描述]
	 */
	@Override
	public List<UpMenus> findMenusBySptype(String userType) {

		if(null != userType){
			if(userType.equals("0")){
				return upMenuJPA.findDefaultResourceWithType("default_sp");
			}
			if(userType.equals("1")){
				return upMenuJPA.findDefaultResourceWithType("default_user");
			}
		}
		return null;
	}
}
